//
//  HWGameCommunityDetailController.m
//  HWanGame
//
//  Created by 王昌健 on 2022/10/20.
//  Copyright © 2022 94Wan. All rights reserved.
//

#import "HWGameCommunityDetailController.h"
#import "HWGameCommunityDetailProtocol.h"
#import <WebKit/WebKit.h>
#import "HWanGame-Swift.h"
@interface HWGameCommunityDetailController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate, WKNavigationDelegate>

@property(strong, nonatomic) HWNavigationView *navView;

@property(strong, nonatomic) HWGameCommunityDetailProtocol *tableViewProtocol;

@property(strong, nonatomic) HWGameCommunityHttpManager *httpManager;

@property (nonatomic, strong) WKWebView     *webView;

@property (nonatomic, strong) UITableView   *tableView;

@property (nonatomic, strong) UIScrollView  *containerScrollView;

@property (nonatomic, strong) UIView        *contentView;

@property (nonatomic, strong) HWGameCommunityDetailTopView        *topView;

@property(strong, nonatomic) HWGameCommunityDetailHeader *tableViewHeader;

@property(strong, nonatomic) HWCommentKeyboardView *keyboardView;

@property(assign, nonatomic) BOOL isReplyUser;

@property(strong, nonatomic) HWGameCommunityDetailCommentModel *replyUserModel;

@end

@implementation HWGameCommunityDetailController {
    
    CGFloat _lastWebViewContentHeight;
    CGFloat _lastTableViewContentHeight;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.httpManager = [[HWGameCommunityHttpManager alloc] init];
        self.tableViewProtocol = [[HWGameCommunityDetailProtocol alloc] init];
        self.isReplyUser = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initValue];
    [self initView];
    [self addObservers];
    
    [self loadData];
    
    [self addAction];
}

- (void)dealloc{
    [self removeObservers];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)initValue{
    _lastWebViewContentHeight = 0;
    _lastTableViewContentHeight = 0;
}

- (void)initView{
    
    self.view.backgroundColor = UIColor.whiteColor;
    
    self.navView = [[HWNavigationView alloc] init];
    [self.navView.backButton setImage:[UIImage imageNamed:@"navBackButton"] forState:UIControlStateNormal];
    self.navView.titleLabel.text = @" ";
    self.navView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:self.navView];
    
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
    }];
    [self.contentView addSubview:self.topView];
    [self.contentView addSubview:self.webView];
    [self.contentView addSubview:self.tableView];
    
    [self.view addSubview:self.containerScrollView];
    [self.containerScrollView addSubview:self.contentView];

    self.contentView.frame = CGRectMake(0, 0, self.view.width, self.view.height * 2);
    self.topView.frame = CGRectMake(0, 0, self.view.width, 105*CFLScaleValue);
    
    self.webView.top = self.topView.height;
    self.webView.height = self.view.height;
    self.tableView.top = self.webView.bottom;
    
    [self.containerScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(self.navView.mas_bottom);
    }];
    
    self.tableViewHeader = [[HWGameCommunityDetailHeader alloc] initWithFrame:CGRectMake(0, 0, 0, 102*CFLScaleValue)];
    self.tableView.tableHeaderView = self.tableViewHeader;
    
    self.keyboardView = [[HWCommentKeyboardView alloc] init];
    [self.view addSubview:self.keyboardView];
    
    [self.keyboardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(54);
        
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotify:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
//    UITapGestureRecognizer *tapBg = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard)];
//
//    let tapBg = UITapGestureRecognizer.init(target: self, action: #selector(closeKeyboard))
//    tempBgView.addGestureRecognizer(tapBg)
}


- (void)loadData {
    [self.httpManager getGameCommunityDetailWithNewsId:self.newsId success:^(HWGameCommunityDetailModel *model) {
        NSString *str = model.content;
        NSData *data = [[NSData alloc]initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
        
        NSString *string =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        
        
        NSString *htmlString = [NSString stringWithFormat:@"<html> \n"
                                    "<head> \n"
                                    "<style type=\"text/css\"> \n"
                                    "body {font-size:15px;}\n"
                                    "</style> \n"
                                    "</head> \n"
                                    "<body>"
                                    "<script type='text/javascript'>"
                                    "window.onload = function(){\n"
                                    "var $img = document.getElementsByTagName('img');\n"
                                    "for(var p in  $img){\n"
                                    " $img[p].style.width = '100%%';\n"
                                    "$img[p].style.height ='auto'\n"
                                    "}\n"
                                    "}"
                                    "</script>%@"
                                    "</body>"
                                    "</html>", string];
        
        [self.webView loadHTMLString:htmlString baseURL:nil];
        
        self.topView.model = model;
        CGFloat height = 102*CFLScaleValue;
        if (model.video.length > 0) {
            height += 163*CFLScaleValue + 10*CFLScaleValue;
        } else {
            if (model.image.count > 0) {
                if (model.image.count > 3) {
                    
                    if (model.image.count > 6) {
                        height += 109*3*CFLScaleValue + 30*CFLScaleValue;
                    } else {
                        height += 109*2*CFLScaleValue + 20*CFLScaleValue;
                        
                    }
                } else {
                    height += 109*CFLScaleValue+10*CFLScaleValue;
                }
            }
        }
        
        self.tableViewHeader.frame = CGRectMake(0, 0, ScreenWidth, height);
        self.tableViewHeader.model = model;
        [self.httpManager getGameCommunityDetailCommentWithNewsId:self.newsId success:^(NSArray<HWGameCommunityDetailCommentModel *> * models) {
            self.tableViewProtocol.models = models;
            [self.tableView reloadData];
        } failure:^(NSString * error) {
            
        }];
    } failure:^(NSString *error) {
        
    }];
    
    
}

- (void)addAction {
    MJWeakSelf;
    self.navView.backButtonClick = ^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    
    self.tableViewHeader.zanButtonClick = ^(HWGameCommunityDetailModel * mod) {
        [weakSelf.httpManager gameCommunityZanWithPid:mod.id puid:mod.uid type:@"0" success:^(NSString * message) {
//            [weakSelf.httpManager getGameCommunityDetailWithNewsId:weakSelf.newsId success:^(HWGameCommunityDetailModel *model) {
//
//                weakSelf.tableViewHeader.model = model;
//            } failure:^(NSString *error) {
//
//            }];
            [weakSelf loadData];
        } failure:^(NSString * error) {

        }];
    };
    
    self.tableViewHeader.commentButtonClick = ^(HWGameCommunityDetailModel * model) {
        [weakSelf.keyboardView.textField becomeFirstResponder];
        weakSelf.isReplyUser = NO;
    };
    
    self.keyboardView.sendText = ^(NSString * text) {
        if (weakSelf.isReplyUser == YES) {
            ///回复人
            [weakSelf.httpManager getGameCommunityCommentAddWithPid:weakSelf.replyUserModel.hid puid:weakSelf.replyUserModel.uid type:@"1" content:text success:^(NSString * message) {
                weakSelf.keyboardView.textField.text = @"";
                [weakSelf.keyboardView.textField endEditing:YES];
            } failure:^(NSString * error) {
    
            }];
        } else {
            ///回复文章
            [weakSelf.httpManager getGameCommunityCommentAddWithPid:weakSelf.newsId puid:weakSelf.newsId type:@"0" content:text success:^(NSString * message) {
                weakSelf.keyboardView.textField.text = @"";
                [weakSelf.keyboardView.textField endEditing:YES];
            } failure:^(NSString * error) {
                
            }];
        }
        
    };
    
    self.tableViewProtocol.replyButtonClick = ^(HWGameCommunityDetailCommentModel * _Nonnull mod) {
        [weakSelf.keyboardView.textField becomeFirstResponder];
        weakSelf.isReplyUser = YES;
        weakSelf.replyUserModel = mod;
    };
    
    self.tableViewProtocol.zanButtonClick = ^(HWGameCommunityDetailCommentModel * _Nonnull mod) {
        [weakSelf.httpManager gameCommunityZanWithPid:mod.hid puid:mod.uid type:@"1" success:^(NSString * message) {
//            [weakSelf.httpManager getGameCommunityDetailCommentWithNewsId:weakSelf.newsId success:^(NSArray<HWGameCommunityDetailCommentModel *> * models) {
//                weakSelf.tableViewProtocol.models = models;
//                [weakSelf.tableView reloadData];
//            } failure:^(NSString * error) {
//
//            }];
            [weakSelf loadData];
        } failure:^(NSString * error) {

        }];
    };
    
    self.tableViewHeader.playButtonClick = ^(HWGameCommunityDetailModel * model) {
        [HWGameCommunityPlayVideo playVideoWithController:weakSelf model:model];
    };
    
    self.tableViewHeader.imageButtonClick = ^(HWGameCommunityDetailModel * model, NSInteger index) {
        [HWGameCommunityPlayVideo clickImageWithController:weakSelf model:model index:index];
    };
}

- (void)keyboardWillChangeFrameNotify:(NSNotification *)notify {
    CGFloat duration = [notify.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardFrame = [notify.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;
    NSLog(@"%f",transformY);
    [UIView animateWithDuration:duration animations:^{
        if (duration == 0.0) {
            self.keyboardView.transform = CGAffineTransformMakeTranslation(0, transformY-54);
//            self.keyboardView.textField.placeholder = "请输入评论内容...";
//            self.keyboardView.textField.text = ""
        } else {
            if (ScreenHeight<812) {
                self.keyboardView.transform = CGAffineTransformMakeTranslation(0, transformY);
            } else {
                if (transformY == 0) {
                    self.keyboardView.transform = CGAffineTransformMakeTranslation(0, transformY+54);
                } else {
                    self.keyboardView.transform = CGAffineTransformMakeTranslation(0, transformY-54);
                }
                
            }
        }
    }];
//    let duration = notify.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
//    let keyboardFrame = notify.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
//    let transformY = keyboardFrame.origin.y - self.view.frame.size.height;
//    UIView.animate(withDuration: duration) {
//
//        if transformY == 0.0 {
//            self.tempBgView.isHidden = true
//            self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY)
//            self.keyboardView.textField.placeholder = "请输入评论内容..."
//            self.keyboardView.textField.text = ""
//            self.ppidModel = nil
//        }else{
//            self.tempBgView.isHidden = false
//            //                self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY + 34)
//            if screenHeight < 812 {
//                self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY)
//
//            }else {
//                self.keyboardView.transform = CGAffineTransform.init(translationX: 0, y: transformY + 34)
//            }
//        }
//     /
//    }
}

- (void)closeKeyboard {
    [self.view endEditing:YES];
}


//
////关闭调用方法的时候网页会放大
//- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
//{
//    NSString *injectionJSString = @"var script = document.createElement('meta');"
//                                   "script.name = 'viewport';"
//                                   "script.content=\"width=device-width, user-scalable=no\";"
//                                   "document.getElementsByTagName('head')[0].appendChild(script);";
//    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
//}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView evaluateJavaScript:@"var a = document.getElementsByTagName('a');for(var i=0;i<a.length;i++){a[i].setAttribute('target','');}" completionHandler:nil];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
#pragma mark - Observers
- (void)addObservers{
    [self.webView addObserver:self forKeyPath:@"scrollView.contentSize" options:NSKeyValueObservingOptionNew context:nil];
    [self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)removeObservers{
    [self.webView removeObserver:self forKeyPath:@"scrollView.contentSize"];
    [self.tableView removeObserver:self forKeyPath:@"contentSize"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if (object == _webView) {
        if ([keyPath isEqualToString:@"scrollView.contentSize"]) {
            [self updateContainerScrollViewContentSize:0 webViewContentHeight:0];
        }
    }else if(object == _tableView) {
        if ([keyPath isEqualToString:@"contentSize"]) {
            [self updateContainerScrollViewContentSize:0 webViewContentHeight:0];
        }
    }
}

- (void)updateContainerScrollViewContentSize:(NSInteger)flag webViewContentHeight:(CGFloat)inWebViewContentHeight{

    CGFloat webViewContentHeight = flag==1 ?inWebViewContentHeight :self.webView.scrollView.contentSize.height;
    CGFloat tableViewContentHeight = self.tableView.contentSize.height;
    
    if (webViewContentHeight == _lastWebViewContentHeight && tableViewContentHeight == _lastTableViewContentHeight) {
        return;
    }
    
    _lastWebViewContentHeight = webViewContentHeight;
    _lastTableViewContentHeight = tableViewContentHeight;
    
    self.containerScrollView.contentSize = CGSizeMake(self.view.width, self.webView.top + webViewContentHeight + tableViewContentHeight);
    
    CGFloat webViewHeight = (webViewContentHeight < self.view.height) ?webViewContentHeight :self.view.height ;
    CGFloat tableViewHeight = tableViewContentHeight < self.view.height ?tableViewContentHeight :self.view.height;
    self.webView.height = webViewHeight <= 0.1 ?0.1 :webViewHeight;
    self.contentView.height = self.webView.top +webViewHeight + tableViewHeight;
    self.tableView.height = tableViewHeight;
    self.tableView.top = self.webView.bottom;
    
    //Fix:contentSize变化时需要更新各个控件的位置
    [self scrollViewDidScroll:self.containerScrollView];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (_containerScrollView != scrollView) {
        return;
    }
    
    CGFloat offsetY = scrollView.contentOffset.y;
    
    CGFloat webViewHeight = self.webView.height;
    CGFloat tableViewHeight = self.tableView.height;
    
    CGFloat webViewContentHeight = self.webView.scrollView.contentSize.height;
    CGFloat tableViewContentHeight = self.tableView.contentSize.height;
    //CGFloat topViewHeight = self.topView.height;
    CGFloat webViewTop = self.webView.top;
    
    CGFloat netOffsetY = offsetY - webViewTop;
    
    if (netOffsetY <= 0) {
        self.contentView.top = 0;
        self.webView.scrollView.contentOffset = CGPointZero;
        self.tableView.contentOffset = CGPointZero;
    }else if(netOffsetY  < webViewContentHeight - webViewHeight){
        self.contentView.top = netOffsetY;
        self.webView.scrollView.contentOffset = CGPointMake(0, netOffsetY);
        self.tableView.contentOffset = CGPointZero;
    }else if(netOffsetY < webViewContentHeight){
        self.contentView.top = webViewContentHeight - webViewHeight;
        self.webView.scrollView.contentOffset = CGPointMake(0, webViewContentHeight - webViewHeight);
        self.tableView.contentOffset = CGPointZero;
    }else if(netOffsetY < webViewContentHeight + tableViewContentHeight - tableViewHeight){
        self.contentView.top = offsetY - webViewHeight - webViewTop;
        self.tableView.contentOffset = CGPointMake(0, offsetY - webViewContentHeight - webViewTop);
        self.webView.scrollView.contentOffset = CGPointMake(0, webViewContentHeight - webViewHeight);
    }else if(netOffsetY <= webViewContentHeight + tableViewContentHeight ){
        self.contentView.top = self.containerScrollView.contentSize.height - self.contentView.height;
        self.webView.scrollView.contentOffset = CGPointMake(0, webViewContentHeight - webViewHeight);
        self.tableView.contentOffset = CGPointMake(0, tableViewContentHeight - tableViewHeight);
    }else {
        //do nothing
        NSLog(@"do nothing");
    }
}

#pragma mark - UITableViewDataSouce
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.backgroundColor = [UIColor redColor];
    }
    
    cell.textLabel.text = @(indexPath.row).stringValue;
    return cell;
}

#pragma mark - private
- (WKWebView *)webView{
    if (_webView == nil) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        
//        configuration.preferences = [WKPreferences new];
//        configuration.preferences.minimumFontSize = 10;
//        configuration.preferences.javaScriptEnabled = YES;
//        configuration.preferences.javaScriptCanOpenWindowsAutomatically = YES;
//
//        //下方代码，禁止缩放
//        WKUserContentController *userController = [WKUserContentController new];
//        NSString *js = @" $('meta[name=description]').remove(); $('head').append( '' );";
//        WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
//        NSMutableString *javascript = [NSMutableString string]; [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
//        [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
//        WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//        [userController addUserScript:script];
//        [userController addUserScript:noneSelectScript];
//        [userController addScriptMessageHandler:self name:@"openInfo"];
//        configuration.userContentController = userController;

        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        
        configuration.userContentController = wkUController;
        
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
        _webView.scrollView.scrollEnabled = NO;
        _webView.scrollView.bounces = NO;
        _webView.scrollView.minimumZoomScale = 1;
        _webView.scrollView.maximumZoomScale = 1;
        _webView.userInteractionEnabled = NO;
        _webView.navigationDelegate = self;
    }
    
    return _webView;
}

- (UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _tableView.delegate = _tableViewProtocol;
        _tableView.dataSource = _tableViewProtocol;
        _tableView.tableFooterView = [UIView new];
        _tableView.scrollEnabled = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;

    }
    return _tableView;
}

- (UIScrollView *)containerScrollView{
    if (_containerScrollView == nil) {
        _containerScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
        _containerScrollView.delegate = self;
        _containerScrollView.alwaysBounceVertical = NO;
        _containerScrollView.minimumZoomScale = 1;
        _containerScrollView.maximumZoomScale = 1;
//        _containerScrollView.bounces = NO;
        _containerScrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    return _containerScrollView;
}

- (UIView *)contentView{
    if (_contentView == nil) {
        _contentView = [[UIView alloc] init];
    }
    
    return _contentView;
}

- (UIView *)topView{
    if (_topView == nil) {
        _topView = [[HWGameCommunityDetailTopView alloc] init];
    }
    
    return _topView;
}
@end

